package com.screen.screendisplay.service.impl.electric;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.screen.screendisplay.entity.electric.ElectricProdoperFuel;
import com.screen.screendisplay.mapper.electric.ElectricProdoperFuelMapper;
import com.screen.screendisplay.service.electric.ElectricProdoperFuelService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.screen.screendisplay.vo.electric.CoalStorageAndAvailableDays;
import com.screen.screendisplay.vo.electric.InventorySituation;
import com.screen.screendisplay.vo.wholeproduct.FuelConsumptionVO;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 燃料情况详情表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class ElectricProdoperFuelServiceImpl extends ServiceImpl<ElectricProdoperFuelMapper, ElectricProdoperFuel> implements ElectricProdoperFuelService {

    /**
     * 燃料进耗存情况
     * @param year
     * @return
     */
    @Override
    public InventorySituation inventorySituation(Integer year) {
        LambdaQueryWrapper<ElectricProdoperFuel> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ElectricProdoperFuel::getYear, year);
        List<ElectricProdoperFuel> list = this.list(lqw);
        InventorySituation inventorySituation = new InventorySituation();
        inventorySituation.setYear(year);
        inventorySituation.setAnnualActualCoalConsumption(BigDecimal.valueOf(
                list.stream().mapToDouble(item ->
                        item.getAnnualActualCoalConsumption().doubleValue()).sum()
        ));
        inventorySituation.setAnnualActualCoalIn(BigDecimal.valueOf(
                list.stream().mapToDouble(item ->
                        item.getAnnualActualCoalIn().doubleValue()).sum()
        ));
        inventorySituation.setAnnualCoalConsumptionCompletionRate(BigDecimal.valueOf(
                list.stream().mapToDouble(item ->
                        item.getAnnualCoalConsumptionCompletionRate().doubleValue()).sum()
        ));
        inventorySituation.setAnnualCoalInOverShortage(BigDecimal.valueOf(
                list.stream().mapToDouble(item ->
                        item.getAnnualCoalInOverShortage().doubleValue()).sum()
        ));
        inventorySituation.setAnnualPlanCoalIn(BigDecimal.valueOf(
                list.stream().mapToDouble(item ->
                        item.getAnnualPlanCoalIn().doubleValue()).sum()
        ));
        inventorySituation.setAnnualCoalInCompletionRate(BigDecimal.valueOf(
                list.stream().mapToDouble(item ->
                        item.getAnnualCoalInCompletionRate().doubleValue()).sum()
        ));
        inventorySituation.setCurrentFuelStock(BigDecimal.valueOf(
                list.stream().mapToDouble(item ->
                        item.getCurrentFuelStock().doubleValue()).sum()
        ));
        inventorySituation.setDailyCoalConsumption(BigDecimal.valueOf(
                list.stream().mapToDouble(item ->
                        item.getDailyCoalConsumption().doubleValue()).sum()
        ));
        return inventorySituation;
    }

    /**
     * 各电厂存煤以及可用天数
     * @param year
     * @return
     */
    @Override
    public List<CoalStorageAndAvailableDays> coalStorageAndAvailableDays(Integer year) {
        LambdaQueryWrapper<ElectricProdoperFuel> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ElectricProdoperFuel::getYear, year);
        List<ElectricProdoperFuel> list = this.list(lqw);
        
        // 按电厂分组统计
        List<CoalStorageAndAvailableDays> resultList = list.stream()
                .collect(java.util.stream.Collectors.groupingBy(
                        item -> item.getPowerPlantCode()
                ))
                .entrySet()
                .stream()
                .map(entry -> {
                    String powerPlantCode = entry.getKey();
                    List<ElectricProdoperFuel> plantDataList = entry.getValue();
                    
                    CoalStorageAndAvailableDays result = new CoalStorageAndAvailableDays();
                    result.setYear(year);
                    result.setPowerPlantCode(powerPlantCode);
                    
                    // 获取电厂名称（取第一个非空的名称）
                    String powerPlantName = plantDataList.stream()
                            .map(ElectricProdoperFuel::getPowerPlantName)
                            .filter(name -> name != null && !name.trim().isEmpty())
                            .findFirst()
                            .orElse("");
                    result.setPowerPlantName(powerPlantName);
                    
                    // 计算全年统计数据
                    // 当前燃料库存：取最新月份的数据
                    BigDecimal currentFuelStock = plantDataList.stream()
                            .filter(item -> item.getCurrentFuelStock() != null)
                            .max((item1, item2) -> Integer.compare(
                                    item1.getMonth() != null ? item1.getMonth() : 0,
                                    item2.getMonth() != null ? item2.getMonth() : 0
                            ))
                            .map(ElectricProdoperFuel::getCurrentFuelStock)
                            .orElse(BigDecimal.ZERO);
                    result.setCurrentFuelStock(currentFuelStock);
                    
                    // 警戒库存：取平均值
                    BigDecimal warningStock = BigDecimal.valueOf(
                            plantDataList.stream()
                                    .filter(item -> item.getWarningStock() != null)
                                    .mapToDouble(item -> item.getWarningStock().doubleValue())
                                    .average()
                                    .orElse(0.0)
                    );
                    result.setWarningStock(warningStock);
                    
                    // 日均耗煤量：取平均值
                    BigDecimal dailyCoalConsumption = BigDecimal.valueOf(
                            plantDataList.stream()
                                    .filter(item -> item.getDailyCoalConsumption() != null)
                                    .mapToDouble(item -> item.getDailyCoalConsumption().doubleValue())
                                    .average()
                                    .orElse(0.0)
                    );
                    result.setDailyCoalConsumption(dailyCoalConsumption);
                    
                    // 库存可用天数：基于当前库存和日均耗煤量计算
                    Integer stockAvailableDays = 0;
                    if (dailyCoalConsumption.compareTo(BigDecimal.ZERO) > 0) {
                        stockAvailableDays = currentFuelStock.divide(dailyCoalConsumption, 0, java.math.RoundingMode.HALF_UP).intValue();
                    }
                    result.setStockAvailableDays(stockAvailableDays);
                    
                    // 警戒可用天数：基于警戒库存和日均耗煤量计算
                    Integer warningAvailableDays = 0;
                    if (dailyCoalConsumption.compareTo(BigDecimal.ZERO) > 0) {
                        warningAvailableDays = warningStock.divide(dailyCoalConsumption, 0, java.math.RoundingMode.HALF_UP).intValue();
                    }
                    result.setWarningAvailableDays(warningAvailableDays);
                    
                    return result;
                })
                .collect(java.util.stream.Collectors.toList());
        
        return resultList;
    }

    /**
     * 获取年度燃料耗存情况（最近5年）
     * @return 年度燃料耗存情况列表
     */
    @Override
    public List<FuelConsumptionVO> getAnnualFuelConsumption() {
        // 从数据库查询年度汇总数据
        List<ElectricProdoperFuel> annualStatsList = baseMapper.getAnnualFuelConsumptionStats();
        
        // 转换为VO对象
        List<FuelConsumptionVO> resultList = new ArrayList<>();
        for (ElectricProdoperFuel entity : annualStatsList) {
            FuelConsumptionVO vo = new FuelConsumptionVO();
            vo.setYear(entity.getYear());
            vo.setCoalConsumption(entity.getAnnualActualCoalConsumption());
            vo.setCoalInCompletion(entity.getAnnualActualCoalIn());
            
            // 计算耗煤完成率：实际耗煤量 / 计划耗煤量 * 100
            if (entity.getAnnualPlanCoalConsumption() != null && 
                entity.getAnnualPlanCoalConsumption().compareTo(BigDecimal.ZERO) != 0) {
                BigDecimal completionRate = entity.getAnnualActualCoalConsumption()
                        .divide(entity.getAnnualPlanCoalConsumption(), 4, RoundingMode.HALF_UP)
                        .multiply(new BigDecimal("100"))
                        .setScale(2, RoundingMode.HALF_UP);
                vo.setCoalConsumptionCompletionRate(completionRate);
            } else {
                vo.setCoalConsumptionCompletionRate(BigDecimal.ZERO);
            }
            
            resultList.add(vo);
        }
        
        return resultList;
    }

}
